package br.usp.pcs.basys.event;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import br.usp.pcs.basys.Job;
import br.usp.pcs.basys.engine.IResources;

public class ReleaseCPUForDisk extends ComputerSystemEvent {

	
	public ReleaseCPUForDisk(Job job, Date date, IResources resources) {
		super(job, date, resources);
	}

	@Override
	List<ActionResult> run() {
		List<ActionResult> result = new ArrayList<ActionResult>();
		resources.releaseProcessor();
		ActionResult releaseProcessor = new ActionResult() {
			public String toString() {
				return "Release Processor";
			}
		};
		result.add(releaseProcessor);
		result.addAll(scheduledNextEvents());
		return result;
	}

	private List<ActionResult> scheduledNextEvents() {
		List<ActionResult> result = new ArrayList<ActionResult>();
		Long duration = job.getMeanOverheadTime();
		Date nextEventDate = getDateAfterWaiting(duration);
		
		ComputerSystemEvent nextEvent = new DiskRequest(job,nextEventDate,resources);
		resources.add(nextEvent);
		result.add(new ScheduledEventResult(nextEvent));
		
		advanceProcessorQueue(nextEventDate);
		ActionResult advanceProcessorQueue = new ActionResult() {
			public String toString() {
				return "Advance Processor Queue";
			}
		};
		result.add(advanceProcessorQueue);
		return result;
	}

	private void advanceProcessorQueue(Date nextEventDate) {
		ProcessorRequest processorRequest = resources.pollProcessorQueue();
		if (processorRequest!=null) {
			processorRequest.setDate(nextEventDate);
			resources.add(processorRequest);
		}
	}

}
